<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="spring" 	uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="tiles" 	uri="http://tiles.apache.org/tags-tiles" %>
<%@ taglib prefix="c"		uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" 	uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html; charset=utf-8" %>
<%@ page language="java" pageEncoding="utf-8"%>

<script type="text/javascript">
$(document).ready(function(){
	setMenuSelection("contracte");
	
// 	alert(getParameter("pId"));
//     var vUid;
//     if (getParameter("pPersonalId")!=null) {
//     	vUid=getParameter("pPersonalId");
//     }
//     else {
//     	vUid=getParameter("pPartenerId");
//     }
    
    
    
    
    	
	feelContracts();

    feelPayments(0);  
});

function feelContracts () {
	
    var vUid;
    if (getParameter("pPersonalId")!=null) {
    	vUid=getParameter("pPersonalId");
    }
    else {
    	vUid=getParameter("pPartenerId");
    }
	
    $("#gridContractsList").kendoGrid({
    	dataSource : {
            type     : "json",
            transport: {
                read: {
                  	 url: "json/listContractForPayments",
                   	 data: { pUid: vUid }
                    }
            },
            schema   : {
                data: "" , 
            	model: {
                	id:"id",
                    fields: {
                    	contractNo: 			{ type: "string" },
                    	contractPerson: 		{ type: "string" },
                    	contractDate: 			{ type: "string" },
                    	amount: 				{ type: "number" },
                    	uprc: 					{ type: "number" },
                    	sum: 					{ type: "number" },
                    	paydAmount: 			{ type: "number" }
                    }
                  }
            }
        },
        columns: [
				{
					field: "id",  							
					title: "#",
					width: 20,
					hidden: true
				},
                {field: "contractNo", 			title: "Nr. contract", 				width: 40},
                {field: "contractPerson", 			title: "Clientul", 				width: 60},
                {field: "contractDate", 		title: "Data contract", 			width: 40},
                {field: "amount", 				title: "Suma contractului (lei)",	width: 40},
                {field: "uprc", 				title: "%", 					width: 20},
                {field: "sum", 					title: "Spre achitare (lei)", 		width: 40},
                {field: "paydAmount", 			title: "Achitat (lei)", 			width: 40}
//                 {	
// 					field:"sum",  						
// 					title: "Achita",
// 					sortable: true,
// 					width: 50,  
//  					template: renderAdd
// 				}
          ],
          height: 400,
          sortable: true,
          pageable: {
        	  pageSize: 10,
        	  pageSizes: [10,15,20],
        	  refresh: true
          },
          //selectable: "row",
          selectable: true,
          change: function () {
			var selected =this.dataItem(this.select()).id;
			feelPayments(selected);
			//alert(this.dataItem(this.select()).sum - this.dataItem(this.select()).paydAmount);
			document.getElementById("pSum").value=this.dataItem(this.select()).sum - this.dataItem(this.select()).paydAmount;
			document.getElementById("pSumMax").value=document.getElementById("pSum").value;
			document.getElementById("pContrId").value=this.dataItem(this.select()).id;
          },
          dataBound: function(e) {
        	    var el = $("#gridContractsList"),
                grid = el.data("kendoGrid"),
                dataSource = grid.dataSource,
                model = dataSource.get(document.getElementById("pContrId").value);

            var row = el.find("tbody>tr[data-uid=" + model.uid + "]");
            grid.select(row); // select the item  
          }
     });
    
    //alert(document.getElementById("pContrId").value);  

}

function  renderAdd (dataItem, b, c) {
	return "<button id='btAddP' type='button' onclick='alert(dataItem.sum)'>Achita</button>";
}

function feelPayments (pContrId) {
    if (pContrId!=null){
    	var pCID=encodeURI(pContrId).replace(/%5B/g, '[').replace(/%5D/g, ']');
    	//alert (pContrId);
	$("#gridPaymentsList").kendoGrid({
    	dataSource : {
            type     : "json",
            transport: {
                read: {
                  	 url: "json/listContractPayments",
                   	 data: {
//                    		 pPersonalId:vUid,
//                    			pPartnerId:vUid,
                   		    pPersonalId: getParameter("pPersonalId"),
                   			pPartnerId : getParameter("pPartenerId"),
                   		    pContractId: pCID
                   	 		}
                    }
            },
            schema   : {
                data: "rows"  
            }
        },
        columns: [
				{
					field:"id",  							
					title: "#",
					width: 40,
					hidden: false
				},
                {field: "amount", 					title: "Suma achitata", 					width: 60},
                {field: "dateTrans", 				title: "Data achitarii", 				width: 60},
                {field: "comments", 				title: "Comentariu", 				width: 200},
                {
					field:"id",  							
					title: "Sterge",
					width: 60,
					template: renderDel
				}
          ],
          height: 275,
          sortable: true,
          pageable: {
        	  pageSize: 10,
        	  pageSizes: [10,15,20],
        	  refresh: true
          }
	
    });
    }
}   

function addPayments() {
	
	if (parseInt(document.getElementById("pSum").value) > parseInt(document.getElementById("pSumMax").value)){
		alert("Suma achitarii ("+document.getElementById("pSum").value+") mai mult decit suma calculata ("+document.getElementById("pSumMax").value+") pe baza procentului!");
		return;
	}
	
    $.ajax({
  	  type: "POST",
  	  url: "json/updContractPayments",
  	  data: { pPersonalId: getParameter("pPersonalId"),
 			pPartnerId: getParameter("pPartenerId"),
   		    pContractId: document.getElementById("pContrId").value,
   		    pAmount: 	 document.getElementById("pSum").value,
   		    pComments:   document.getElementById("pComment").value }
  	}).done(function() {
  	  //$( this ).addClass( "done" );
  		//alert("done");
//   		var row = $("#gridContractsList").select();
//         var id = row.data("id"); 
//   		var secondGrid = $("#gridContractsList").data("kendoGrid");
//         var row = secondGrid.table.find('tr[data-id="' + id + '"]');
//       alert(row);
//       secondGrid.select(row);
  		feelContracts();
  	    feelPayments(document.getElementById("pContrId").value); 

  	  	document.getElementById("pSum").value="";
  	    document.getElementById("pComment").value="";
  	});
}

function delPayments(pId) {
	
    $.ajax({
  	  type: "POST",
  	  url: "json/delContractPayments",
  	  data: { pId: pId }
  	}).done(function() {
  		feelContracts();
  	    feelPayments(document.getElementById("pContrId").value); 
  	});
}

function  renderDel (dataItem, b, c) {
	//var vId =dataItem.id;
	return '<button id="btDelP" type="button" onclick="delPayments('+dataItem.id+')">Sterge</button>';
}

function  testt(){ 
// 	console.debug('id..'+document.getElementById("pContrId").value);
// 	var secondGrid = $("#gridContractsList").data("kendoGrid");
// 	console.debug('greed..'+secondGrid.dataSource.total());
// 	var row = secondGrid.table.find('tr[data-id="'+document.getElementById("pContrId").value+'"]');
// 	console.debug('row..'+row.data("id"));
// 	secondGrid.select(row);

// 	 var grid = $("#gridContractsList").data("kendoGrid"),
//      //row = grid.tbody.find(">tr:not(.k-grouping-row)").eq(2);
// 	 row = grid.table.find('tr[data-id="' + document.getElementById("pContrId").value + '"]');
// 	 grid.select(row);

    var el = $("#gridContractsList"),
        grid = el.data("kendoGrid"),
        dataSource = grid.dataSource,
        model = dataSource.get(document.getElementById("pContrId").value); // get the model
//         index = dataSource.indexOf(model); // get the index of the item into the DataSource
    
//     dataSource.page(index/dataSource.pageSize() + 1);  //page to the item  

    var row = el.find("tbody>tr[data-uid=" + model.uid + "]");
    grid.select(row); // select the item  
}
</script>

<CENTER>

<c:if test="${personalItem.id!=null}">
	Achitari pe consultant
	
	<form:form id="formPersonalCard" commandName="personalItem">
	<div class="k-block k-shadow">
				<ul class="forms" style="font-size: 14px;">
					<div class="k-block"><div class="k-header k-shadow">Datele consultantului</div>
	
	<!-- 			 Date personale -->
	<left>
	<table width="100%">
		<tr>
			<td align="left">
				Cod personal:<form:input type="text" id="pIdnp" 	 		path="idnp" maxlength="13" style="width:150px;" class="k-textbox" required="true" readonly="readonly"/> 
			</td>
	
			<td>
				Nume:<form:input type="text" id="pLastName" 		path="lastName"  	name="lastName" style="width:250px;"  class="k-textbox"  required="true"/>
			</td>
			<td>
				Prenume:<form:input type="text" id="pFirstName" 	path="firstName" 	name="firstName" style="width:250px;"  class="k-textbox"  required="true"/>
			</td>
			<td>		  
				Patronimic:<form:input type="text" id="pPatronymic" 	path="patronymic"  	name="patronymic" style="width:250px;"  class="k-textbox"  /> 
			</td>
		</tr>
	</table>
	</left>
	</div>
	</ul>
	</div>
	</form:form>
</c:if>


<c:if test="${partenerItem.id!=null}">
	Achitari pe partener
	
	<form:form id="formPartenerCard" commandName="partenerItem">
	<div class="k-block k-shadow">
				<ul class="forms" style="font-size: 14px;">
					<div class="k-block"><div class="k-header k-shadow">Datele partenerului</div>
	
	<!-- 			 Date personale -->
	<left>
	<table width="100%">
		<tr>
			<td align="left">
				IDNO:<form:input type="text" id="pIdno" 	 		path="idno" maxlength="13" style="width:150px;" class="k-textbox" required="true" readonly="readonly"/> 
			</td>
	
			<td>
				Denumire:<form:input type="text" id="pName" 		path="companyName"  	name="companyName" style="width:750px;"  class="k-textbox"  required="true"/>
			</td>

		</tr>
	</table>
	</left>
	</div>
	</ul>
	</div>
	</form:form>
</c:if>

<table width="100%">
	<tr>
		<td>Contracte</td>
		<td>Achitari pe contract</td>
	</tr>
	<tr>
		<td align="left" width="50%">
			<div id="gridContractsList"></div> 
  		</td>
  		<td align="left" width="50%">
			<div id="gridPaymentsList"></div> 
			<br>
			<div class="k-block"><div class="k-header k-shadow"><b>Adaugarea achitarii</b></div>
			<font color="red"><b>Suma spre achitare:</b></font>
			<input type="text" id="pSum" maxlength="10" style="width:150px;" class="k-textbox" /> 
			<input type="hidden" id="pSumMax"/> 
			<input type="hidden" id="pContrId"/> 
			<button id="btAdd" type="button" onclick="addPayments();">Achitat</button>
<!-- 			<button id="btAdd11" type="button" onclick="testt();">testt</button> -->
			<br><br>
			<font color="black"><b>Comentariu:</b></font>
			<input type="text" id="pComment" maxlength="500" style="width:550px;" class="k-textbox" />
			
			<br>
			</div>
  		</td>
	</tr>
</table>

</CENTER>
<style scoped>
     #formPersonsCard ul {
         list-style-type: none;
         margin: 0;
         padding: 0;
     }
     #formPersonsCard li {
         margin: 10px 0 0 0;
     }

     label {
         display: inline-block;
         width: 300px;
         text-align: right;
     }
     
     input {
     	height: 10px;
     }

     .required {
         font-weight: bold;
     }

     .accept, .status {
         padding-left: 90px;
     }

     .valid {
         color: green;
     }

     .invalid {
         color: red;
     }
     span.k-tooltip {
         margin-left: 6px;
     }
 </style>
